export default {
    name: "update",
    setup(props) {
        const router = VueRouter.useRouter();
        const status = ref('');
        const fileList = ref([]);
        const dialogVisible = ref(false);
        const checkLoading = ref(false);    // 检查按钮加载状态
        const updateLoading = ref(false);   // 更新按钮加载状态
        
        // 检查更新
        const checkUpdate = _.debounce(async () => {
            if(window.APP_CONFIG.baseurl == 'https://zp.kzhgzs.cn/') {
                return ElMessage.error('演示站禁止更新');
            }
            try {
                checkLoading.value = true;  // 开始加载
                const res = await checkupdate();
                if (res && res.length) {
                    fileList.value = res;
                    ElNotification({
                        title: '发现新版本',
                        message: `${res.length} 个文件待更新`,
                        type: 'success'
                    });
                } else {
                    ElNotification({
                        title: '版本检查',
                        message: '当前已是最新版本',
                        type: 'info'
                    });
                }
            } finally {
              checkLoading.value = false;
            }
        }, 500);

        // 应用更新
        const applyUpdate = async () => {
            dialogVisible.value = true;
        };

        const confirmUpdate = async () => {
            if(window.APP_CONFIG.baseurl === 'https://zp.kzhgzs.cn/') {
                return ElMessage.error('演示站禁止更新');
            }
            status.value = '正在下载更新包...';
            // 创建全屏Loading实例
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '系统升级中，请勿关闭页面...',
                background: 'rgba(0, 0, 0, 0.8)',
                spinner: 'el-icon-loading' // 可选加载图标
            });
            try {
                updateLoading.value = true;  // 开始更新
                const res = await updatefiles(fileList.value);
                ElNotification({
                    title: '更新启动',
                    message: '系统将在更新完成后自动重启',
                    type: 'success',
                    duration: 0
                });
                await restart();
                dialogVisible.value = false;
                // 10秒后执行刷新
                setTimeout(() => {
                    loadingInstance.close(); // 先关闭loading
                    window.location.reload();
                }, 10000);
            } catch (error) {
                updateLoading.value = false;
                loadingInstance.close(); // 发生错误时关闭loading
                ElMessage.error(`更新失败: ${error.message}`);
            }
        };

        onMounted(() => {
            checkUpdate();
        });

        return {
            status,
            fileList,
            dialogVisible,
            checkUpdate,
            applyUpdate,
            confirmUpdate,
            checkLoading,
            updateLoading,
            actionTypeMap: {
                create: 'success',
                update: 'warning',
                delete: 'danger'
            },
            actionTextMap: {
                create: '新增',
                update: '修改',
                delete: '删除'
            },
        };
    },
    template: `
<el-card>
    <template #header>
        <div style="display: flex;justify-content: space-between;align-items: center;padding: 0 10px;">
            <span style="font-size: 1.2rem;font-weight:500">系统更新</span>
            <el-button type="primary" @click="checkUpdate" v-if="fileList.length == 0">检查更新</el-button>
        </div>
    </template>

    <el-empty v-if="!fileList.length" description="暂无更新信息" />

    <div v-else style="display: flex;flex-direction: column;gap: 20px;">
        <el-alert :title="'发现新版本，' + fileList.length + '个文件待更新'" type="success" :closable="false" show-icon></el-alert>

        <el-table :data="fileList" height="850px" style="width: 100%" stripe>
            <el-table-column label="更新类型" width="120" align="center" prop="action">
                <template #default="{row}">
                    <el-tag :type="actionTypeMap[row.action]" effect="dark" size="small">{{ actionTextMap[row.action] || '' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="path" label="文件路径" />
            <el-table-column label="文件大小" width="120">
                <template #default="{row}">{{ (row.size/1024).toFixed(1) }} KB</template>
            </el-table-column>
            <el-table-column prop="hash" label="哈希校验" />
        </el-table>

        <div style="margin-top: 30px;text-align: center;">
            <el-button type="success" size="large" @click="applyUpdate" :disabled="status.includes('启动')">
                <el-icon><Download /></el-icon>立即更新
            </el-button>
        </div>
    </div>

    <el-dialog v-model="dialogVisible" title="确认更新" width="30%">
        <span>确认要立即更新吗？</span>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmUpdate">确认</el-button>
        </template>
    </el-dialog>
</el-card>
`
}